<?php
// 【最终完整版】m-merchant/send_sms_handler.php
session_start();
header('Content-Type: application/json; charset=utf-8');

function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%';
    if (!$token) return null; $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null; list($h, $p, $s) = $token_parts;
    $sig = base64_decode(str_replace(['-','_'],['+','/'], $s));
    $exp_sig = hash_hmac('sha256', $h.".".$p, $secret_key, true);
    if (!hash_equals($exp_sig, $sig)) return null;
    $payload = json_decode(base64_decode(str_replace(['-','_'],['+','/'], $p)), true);
    if ($payload === null || ($payload['exp']??0) < time()) return null;
    return $payload['data'];
}
function get_authorization_header() {
    if (isset($_SERVER['Authorization'])) return trim($_SERVER["Authorization"]);
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) return trim($_SERVER["HTTP_AUTHORIZATION"]);
    if (function_exists('getallheaders')) {
        $h = getallheaders(); if (isset($h['Authorization'])) return trim($h['Authorization']);
    } return null;
}
$user_data = verify_token(str_replace('Bearer ', '', get_authorization_header()));
if ($user_data === null) { http_response_code(401); echo json_encode(['code' => -99, 'msg' => '登录失效']); exit(); }

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$smsUser = "xiaolong106"; 
$smsPass = "b7816e35da9f4ba9adb9952434da01b6";
$phoneNumber = $_POST["phoneNumber"] ?? '';
if (empty($phoneNumber) || !preg_match('/^1[3-9]\d{9}$/', $phoneNumber)) {
    echo json_encode(["code" => 400, "msg" => "请输入有效的手机号"]); exit;
}

$verificationCode = mt_rand(100000, 999999);
$_SESSION['sms_code'] = $verificationCode;
$_SESSION['sms_phone'] = $phoneNumber;

$content = "【您的应用名】您的验证码是" . $verificationCode . "，5分钟内有效。";
$api_url = "https://api.smsbao.com/sms";
$query_data = http_build_query(['u' => $smsUser, 'p' => md5($smsPass), 'm' => $phoneNumber, 'c' => $content]);
$requestUrl = $api_url . '?' . $query_data;

$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$response_sms = curl_exec($ch);
curl_close($ch);

if ($response_sms == '0') {
    echo json_encode(["code" => 200, "msg" => "验证码发送成功"]);
} else {
    echo json_encode(["code" => 400, "msg" => "验证码发送失败，服务商错误码: " . $response_sms]);
}
mysqli_close($con);
?>